const qiniu = require("qiniu");
const { qiniuConfig } = require('./config');

// 配置七牛云构造函数对象
function QnMeans() {
    var mac = new qiniu.auth.digest.Mac(qiniuConfig.AccessKey, qiniuConfig.SecretKey);
    var options = {
        scope: qiniuConfig.bucket
    };
    var config = new qiniu.conf.Config();
    config.zone = qiniu.zone[qiniuConfig.Zone];
    var putPolicy = new qiniu.rs.PutPolicy(options);
    this.uploadToken = putPolicy.uploadToken(mac);
    this.formUploader = new qiniu.form_up.FormUploader(config);
    this.putExtra = new qiniu.form_up.PutExtra();
}

// 文件上传(服务端存在的文件上传七牛云)
const formUploaderFile = function(key, path) {
    let qn = new QnMeans;
    return new Promise((reslove, reject) => {
        qn.formUploader.putFile(qn.uploadToken, key, path, qn.putExtra, function(respErr, respBody, respInfo) {
            if (respErr) {
                reject(respErr);
            }
            if (respInfo.statusCode == 200) {
                reslove(respBody)
                console.log(respBody);
            } else {
                reject(respInfo.statusCode, respBody);
                console.log(respInfo.statusCode);
                console.log(respBody);
            }
        });
    });
}
// 数据流上传（表单方式）文件流直接上传七牛云
const readableStreamUpload = function(key, readableStream) {
    let qn = new QnMeans;
    return new Promise((reslove, reject) => {
        qn.formUploader.putStream(qn.uploadToken, key, readableStream, qn.putExtra, function(respErr, respBody, respInfo) {
            if (respErr) {
                reject(respErr);
            }
            if (respInfo.statusCode == 200) {
                reslove(respBody)
            } else {
              console.log(respInfo.statusCode);
              reslove(respBody)
            }
        })

    })
}

module.exports = {
    formUploaderFile,
    readableStreamUpload
}